package com.barry.io.utils;

import java.io.IOException;
import java.util.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.alibaba.dashscope.aigc.multimodalconversation.*;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 通义千问VL-Max模型的视觉理解能力最强
 * 参考: https://help.aliyun.com/zh/model-studio/vision/#474a5231a7jjj
 * 根据本地图片进行AI诊断分析
 * */
@Slf4j
public class LocalImageDiagnosis {

    private static String encodeImageToBase64(String imagePath) throws IOException {
        Path path = Paths.get(imagePath);
        byte[] imageBytes = Files.readAllBytes(path);
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static void callWithLocalFile(String localPath) throws ApiException, NoApiKeyException, UploadFileException, IOException {

        String base64Image = encodeImageToBase64(localPath); // Base64编码

//        String text = "根据舌面进行中医AI诊断，出一个JSON格式报告，报告维度有体质名称，中医证型，健康分值，体质分析，典型特征，风险预警，异常分析，调理建议等, " +
//                "请把接口返回的MultiModalConversationResult中的MultiModalMessage的内容text内容以JSON格式返回。";
        String text = "根据舌面进行中医AI诊断，诊断报告内容有体质名称，中医证型，健康分值，体质分析，典型特征，风险预警，异常分析，调理建议等, " +
                "要求诊断报告结果只能以JSON格式输出，不能出现非JSON格式的内容出现。";
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMessage = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant."))).build();

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        new HashMap<String, Object>() {{ put("image", "data:image/png;base64," + base64Image); }},
                        new HashMap<String, Object>() {{ put("text", text); }}
                )).build();

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                .apiKey(Const.ALI_BAI_LIAN_API_KEY)
                .model(Const.ALI_BAI_LIAN_MODEL_VL_MAX)
                .messages(Arrays.asList(systemMessage, userMessage))
                .build();

        MultiModalConversationResult result = conv.call(param);
        String resp = (String) result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text");
        log.info("千问大模型API返回值为: {}", resp);
        if (StringUtils.isNotBlank(resp)) {
            String content = resp;
            int index = content.lastIndexOf("}")+ 1;
            log.info("数据处理[index]为: {}", index);
            content = content.substring(0, index);
            content = content.replaceAll("```json", "");
            log.info("数据处理[content]为: {}", content);

            Map<String, Object> map = JSON.parseObject(content, Map.class);
            String constitutionName = map.get("体质名称").toString();
            String syndromeType = map.get("中医证型").toString();
            int healthScore = (int) map.get("健康分值");
            String constitutionAnalysis = map.get("体质分析").toString();
            String typicalFeatures = map.get("典型特征").toString();
            String riskWarning = map.get("风险预警").toString();
            String abnormalAnalysis = map.get("异常分析").toString();
            String conditioningSuggestions = map.get("调理建议").toString();
            log.info("体质名称: {}", constitutionName);
            log.info("中医证型: {}", syndromeType);
            log.info("健康分值: {}", healthScore);
            log.info("体质分析: {}", constitutionAnalysis);
            log.info("典型特征: {}", typicalFeatures);
            log.info("风险预警: {}", riskWarning);
            log.info("异常分析: {}", abnormalAnalysis);
            log.info("调理建议: {}", conditioningSuggestions);
        }

    }

    public static void main(String[] args) {
        try {
            // 将 xxx/eagle.png 替换为你本地图像的绝对路径
            String filePath = "D:\\面舌AI诊断\\images\\mianshe001.jpg";
            callWithLocalFile(filePath);
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            log.error("图片诊断解析报错: {}", e.getMessage(), e);
        }
        System.exit(0);
    }
}